(function () {
    window.pageProductAll = [];
    function omesaasProduct(option) {
        if (!option.product || option.product instanceof Array) {
            return false;
        }
        window.pageProductAll.push(this);

        this.product = option.product;

        this.optionLength = option.product.options.length;

        this.params = {
            spu: this.product.spu,
            quantity: option.quantity || 1,
            price: option.product.variant_price_min,
            src: option.product.src,
            is_main_product: option.isMainProduct || false,
            block_id: option.block_id || "",
            productTitle: option.product.title,
            product_id: option.product.id
        };

        this.attrOption = []; 

        this.oldAttrOption = []; 

        this.multiple = []; 

        this.cartShake = true; 

        this.buyShake = true; 

        this.wishlistShake = true;

        this.renderFirst = true; 

        this.changeOption = option.changeOption; 

        this.isMainProduct = option.isMainProduct || false; 

        this.block_id = option.block_id || new Date().getTime(); 

        this.data_from = option.data_from || ""; 

        this.ec_currency_code = option.ec_currency_code || ""; 

        
        this.variant = option.product.variants; 

        this.renderOption = option.renderOption === undefined? true:option.renderOption; 

        this.wishlist = option.wishlist || ""; 

        this.productOptionType = option.productOptionType || "default";

        
        
        
        
        

        
        if (this.renderOption) {
            this.formDom = $(option.id);

            this.numberNode = this.formDom.find(".product-price-number");

            this.skuValueNode = $(".product-detail-skuspu .sku");

            this.marketNode = this.formDom.find(".product-price-market");

            this.discountNode = this.formDom.find(".product-price-discount");

            this.skuNode = this.formDom.find(".sku-cell");

            if (option.productOptionType === "global" || option.productOptionType === undefined) {
                this.productOptionType = themeConfig.global.product_option_type;
            }

            
            if (this.isMultiple() ) {
                if(this.isMainProduct){
                    $(".control-product_detail-quantity_box").remove();
                }
                const that = this;
                
                moi.addEvent("paypalec_multiple_callback",function(event){
                    if(event.params.payId === that.block_id){
                        if(that.verifyOption()){
                            event.params['data'] = that.multiple.filter(el=>el.add_quantity>0);
                            event.params['code'] = 200;
                        }else{
                            event.params['code'] = 400;
                        }
                    }
                })
            }

            const oldTempID = `#omesaas-product-sku-${this.productOptionType}`;
            const newTempID = `#id-product-sku-${this.productOptionType}`;
            this.skuTemplate = $(newTempID).length?$(newTempID).html():$(oldTempID).html()

            const self = this;
            this.skuNode.on("click", ".product-sku-values-item", function () {
                self.renderFirst = false;
                
                const index = $(this).data("index");
                const idx = $(this).data("idx");
                const item = self.attrOption[index - 1].value[idx - 1];
                // const item = self.attrOption[index - 1];
                // $(this).addClass("product-sku-values-item-active").siblings().removeClass("product-sku-values-item-active");

                

                
                if (storeConfig.checked_first_sku == 2 && self.attrOption[index - 1].selected_value == item.value) {
                    self.attrOption[index - 1].selected_value = "";
                    self.attrOption[index - 1].selected_value_label = "";
                    
                    
                    
                    
                    
                    
                    
                    
                } else {
                    self.attrOption[index - 1].selected_value = item.value;
                    self.attrOption[index - 1].selected_value_label = item.name;
                }
                
                for (let i = 0; i < self.optionLength; i++) {
                    self.attrOption[i].value = [];
                }
                self.setSkuOption();

                if (item.deleteItem) {
                    if ($(this).hasClass("product-sku-values-item-active") && storeConfig.checked_first_sku == 2) {
                        self.attrOption[index - 1].selected_value = "";
                        self.attrOption[index - 1].selected_value_label = "";
                    } else {
                        self.attrOption[index - 1].selected_value = item.value;
                        self.attrOption[index - 1].selected_value_label = item.name;
                    }
                }
            });

            this.skuNode.on("change", ".product-sku-unselect", function () {
                self.renderFirst = false;
                const item = $(this).find("option:selected").data("value");
                const index = $(this).find("option:selected").data("index");

                if (storeConfig.checked_first_sku == 2) {
                    $(this).siblings("svg").show();
                    $(this).siblings(".mo-edge").hide();
                } else {
                    $(this).siblings("svg").hide();
                    $(this).siblings(".mo-edge").show();
                }
                
                if (!self.isCurrentOptionBuy(item)) {
                    return false;
                }
                self.attrOption[index - 1].selected_value = item.value;
                for (let i = 0; i < self.optionLength; i++) {
                    self.attrOption[i].value = [];
                }
                self.setSkuOption();
            });

            this.skuNode.on("change", "input[name='sku_option-template_all']", function () {
                self.renderFirst = false;
                const value = $(this).val();
                const currentVariant = self.variant.find((el) => el.sku_code === value);
                self.setSelectedVal(currentVariant);
                self.setPriceVal(currentVariant);
            });
        }

        
        if (this.wishlist) {
            this.wishlistEvent();
        }
        this.initSku();

        if(oemcart_page_ca === 'product_detail' && storeConfig.comments_status == '1' && this.isMainProduct ) {
            this.setCommentStar();
        }
    }
    omesaasProduct.prototype.isMultiple = function () {
        if(this.optionLength && this.productOptionType === "multiple" && this.optionLength <= 2){
            return  true
        }
        return false
    };
    omesaasProduct.prototype.event = function () {
        const self = this;
        this.skuNode.find(".product-sku-select-delete").click(function (event) {
            event.stopPropagation();
            event.preventDefault();
            $(this).hide();
            $(this).siblings(".mo-edge").show();
            self.renderFirst = false;
            const select = $(this).siblings(".product-sku-unselect");
            select.val(0);
            const index = $(this).data("index");
            self.attrOption[index - 1].selected_value = "";
            self.attrOption[index - 1].selected_value_label = "";
            for (let i = 0; i < self.optionLength; i++) {
                self.attrOption[i].value = [];
            }
            self.setSkuOption();
        });

        this.skuNode.on("click", ".step-warp-handle", function (event) {
            event.stopPropagation();
            event.preventDefault();
            var keys = $(this).parent().data("keys").split(",");
            var type = $(this).data("type");
            var valueDom = $(this).siblings(".step-warp-value");
            var item = self.attrOption[keys[0]].value[keys[1]];
            var value = parseInt(valueDom.val()) || 0;
            
            let isMaxInventory = (self.product.inventory_policy == 2 && self.product.inventory_tracking == 1) ||  self.product.inventory_tracking == 0

            if (type == "minus" && value > 0) {
                valueDom.val(--value);
                if (!value) {
                    $(this).attr("disabled", true);
                }

                if (item.quantity != 0 && item.available && value <= item.quantity) {
                    $(this).siblings(".step-warp-handle[data-type='plus']").removeAttr("disabled");
                }
                
                if((self.product.inventory_policy == 2 && self.product.inventory_tracking == 1) ||  self.product.inventory_tracking == 0) {
                    if(value < 99999) {
                        $(this).siblings(".step-warp-handle[data-type='plus']").removeAttr("disabled");
                    }
                }
            }
            if (type == "plus") {
                if (self.productOptionType === "multiple" ) {
                    
                    for (let i = 0; i < self.attrOption.length; i++) {
                        if (!self.attrOption[i].selected_value && self.attrOption[i].type != "multiple" ) {
                            $("html, body").animate({ scrollTop: self.skuNode.find(".product-sku-name").eq(i).offset().top - 200 });
                            moi.tooltip({
                                placement: "right",
                                el: self.skuNode.find(".product-sku-name").eq(i),
                                content: lang.product.please_select_sku.replace("{sku}", self.product.options[i].name)
                            });
                            return ;
                        }
                    }
                }

                valueDom.val(++value);
                if (value) {
                    $(this).siblings(".step-warp-handle[data-type='minus']").removeAttr("disabled");
                }

                
                if (item.quantity != 0 && item.available && value >= item.quantity && !isMaxInventory) {
                    $(this).attr("disabled", true);
                }
                
                if(isMaxInventory) {
                    if(value >= 99999) {
                        value = 99999;
                        $(this).attr("disabled", true);
                    }
                }
            }

            item["add_quantity"] = value;
            self.pushMultiple(item);
            self.multipleTotalPrice();
        });

        this.skuNode.on("input", ".step-warp-value", function (event) {
            event.stopPropagation();
            event.preventDefault();

            var keys = $(this).parent().data("keys").split(",");
            var item = self.attrOption[keys[0]].value[keys[1]];
            var value = parseInt($(this).val());
            if (isNaN(value)) {
                return false;
            }
            if (parseInt(value) < 0) {
                value = 0;
            }

            
            let isMaxInventory = (self.product.inventory_policy == 2 && self.product.inventory_tracking == 1) ||  self.product.inventory_tracking == 0
            
            if (item.quantity != 0 && item.available && value >= item.quantity && !isMaxInventory) {
                value = item.quantity;
                $(this).siblings(".step-warp-handle[data-type='plus']").attr("disabled", true);
            }
            
            if(isMaxInventory) {
                if(value >= 99999) {
                    value = 99999;
                    $(this).siblings(".step-warp-handle[data-type='plus']").attr("disabled", true);
                }else {
                    $(this).siblings(".step-warp-handle[data-type='plus']").removeAttr("disabled");
                }
            }

            if (!value) {
                $(this).siblings(".step-warp-handle[data-type='minus']").attr("disabled", true);
                $(this).siblings(".step-warp-handle[data-type='plus']").removeAttr("disabled");
            } else {
                $(this).siblings(".step-warp-handle[data-type='minus']").removeAttr("disabled");
            }

            $(this).val(value);

            item["add_quantity"] = parseInt(value);
            self.pushMultiple(item);
            self.multipleTotalPrice();
        });

        this.skuNode.on("blur", ".step-warp-value", function (event) {
            event.stopPropagation();
            event.preventDefault();

            var keys = $(this).parent().data("keys").split(",");
            var item = self.attrOption[keys[0]].value[keys[1]];
            var value = parseInt($(this).val());
            if (isNaN(value)) {
                var current = self.multiple.find((el) => el.id == item.id);
                $(this).val(current ? current.add_quantity : 0);
                return false;
            }
        });

        this.skuNode.on("click", ".multiple-reset", function (event) {
            event.stopPropagation();
            event.preventDefault();
            var selected_value = 0;
            if (self.attrOption.length >= 2) {
                selected_value = self.attrOption[0].selected_value;
            }
            $(".moi-product-sku-multiple .step-warp-value").val(0);
            $(".moi-product-sku-multiple .step-warp-handle[data-type='minus']").attr("disabled", true);
            self.resetMultiple(selected_value);
            self.multipleTotalPrice();
        });

        
        this.skuNode.on("mouseenter", ".stock-sotes", function (event) {
            event.stopPropagation();
            moi.tooltip({
                placement: "top-center",
                isDefaultRemove: false,
                elClass: 'stock-sotes-tooltip',
                el: $(this),
                content: !self.product.inventory_tracking && self.product.inventory_policy != 2?lang.general.not_track_inventory:lang.general.stock_allowed
            });
        });
        this.skuNode.on("mouseleave", ".stock-sotes", function (event) {
            event.stopPropagation();
            $('.stock-sotes-tooltip').remove();
        });

    };

    omesaasProduct.prototype.initSku = function () {
        const self = this;
        const copyList = JSON.parse(JSON.stringify(this.variant));

        
        if (this.product.spec_mode === 1) {
            copyList[0]["image"] = "";
        }

        
        let FirstPriceItemIndex = this.getSelectedIndex();

        const checkedSkuInfo = this.checkedSKu();
        if (!copyList.length) {
            console.log("数据异常");
            return;
        }
        if (this.optionLength) {
            
            const selected = FirstPriceItemIndex === -1 ? false : this.isCurrentOptionBuy(copyList[FirstPriceItemIndex]);

            for (let i = 0; i < this.optionLength; i++) {
                var selected_value = "";
                var selected_value_label = "";

                
                if (selected && storeConfig.checked_first_sku != 2) {
                    selected_value = copyList[FirstPriceItemIndex][`option${i + 1}_value`];
                    selected_value_label = copyList[FirstPriceItemIndex][`option${i + 1}_value_title`];
                }
                
                if (checkedSkuInfo) {
                    selected_value = checkedSkuInfo[`option${i + 1}_value`];
                    selected_value_label = checkedSkuInfo[`option${i + 1}_value_title`];
                }
                
                
                

                this.attrOption.push({
                    name: "",
                    isImg: false,
                    selected_value_label: selected_value_label,
                    selected_value: selected_value,
                    value: []
                });
            }

            this.setSkuOption();
        } else {
            this.setSelectedVal(copyList[0]);
            this.setPriceVal(copyList[0]);
        }
    };

    
    omesaasProduct.prototype.getSelectedIndex = function () {
        const copyList = this.variant;
        const availableVariants = copyList.filter(item => item.available);
        let FirstPriceItemIndex = 0;
        if (this.product.inventory_policy !== 2 && this.product.inventory_tracking === 1) {
            FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);
        }
        
        if(storeConfig.checked_first_sku == 3){
            FirstPriceItemIndex = copyList.findIndex(item =>
                item.available &&
                item.price === Math.min(...availableVariants.map(v => v.price))
            );
        }

        
        if(storeConfig.checked_first_sku == 4){
            FirstPriceItemIndex = copyList.findIndex(item =>
                item.available &&
                item.price === Math.max(...availableVariants.map(v => v.price))
            );
        }

        
        if(storeConfig.checked_first_sku == 5){
            FirstPriceItemIndex = copyList.findIndex(item =>
                item.available &&
                item.inventory_quantity === Math.max(...availableVariants.map(v => v.inventory_quantity))
            );
        }
        return FirstPriceItemIndex !== -1 ? FirstPriceItemIndex : 0;
    }

    omesaasProduct.prototype.setCommentStar = function() {
        $(`.control-product_detail-comment_star .moi-start-warp.moi-start-warp-underline>span:last`).on('click', function () {
            if(!$('#product-tabs .moi-tabs-item[data-type="comment"]').hasClass('moi-tabs-active')) {
                $('#product-tabs .moi-tabs-item[data-type="comment"] .moi-tabs-title').trigger('click');
            }
            let offsetTop = 0
            offsetTop = document.querySelector('#product-tabs .moi-tabs-item[data-type="comment"]').offsetTop + document.querySelector('.product-tabs-card').offsetTop
            window.scrollTo(0, offsetTop)
        })

        
        function openMobileComment() {
            if (!$('.module-cell[data-type=comment]').hasClass('module-cell-active')) {
                $('.module-cell[data-type=comment] .module-cell-header').click()
            }
        }
    }

    
    
    omesaasProduct.prototype.setButtonGroup = function (item, type = "stockout") {
        if(!this.product.status){
            return false
        }
        if (type == "delete") {
            this.formDom.find(".product-payment-box").hide();
            this.formDom.find(".product-cart-group").hide();
            this.formDom.find(".product-out-of-stock").hide();
            this.formDom.find(".product-out-of-delete").show();
            return false;
        } else {
            this.formDom.find(".product-out-of-delete").hide();
        }
        if (item.available && type == null) {
            this.formDom.find(".product-cart-group").show();
            this.formDom.find(".product-payment-box").show();
            this.formDom.find(".product-out-of-stock").hide();
        } else {
            if (storeConfig.product_put_off_control == "buy" && !this.product.available) {
                this.formDom.find(".product-cart-group").show();
                this.formDom.find(".product-payment-box").show();
                this.formDom.find(".product-out-of-stock").hide();
            } else {
                this.formDom.find(".product-payment-box").hide();
                this.formDom.find(".product-cart-group").hide();
                this.formDom.find(".product-out-of-stock>div").text(lang.product.out_of_stock);
                this.formDom.find(".product-out-of-stock").show();
            }
        }
    };

    
    omesaasProduct.prototype.checkedSKu = function (item) {
        const barcode = moi.getUrlParam("variant_barcode");
        const sku = moi.getUrlParam("variant_sku");
        const sku_code = moi.getUrlParam("variant_sku_code");

        if (barcode === "" && sku === "" && sku_code === "") {
            return false;
        }

        if (sku_code) {
            return this.variant.find(function (el) {
                return el.sku_code === sku_code;
            });
        }

        if (sku) {
            return this.variant.find(function (el) {
                return el.sku === sku;
            });
        }

        if (barcode) {
            return this.variant.find(function (el) {
                return el.barcode === barcode;
            });
        }
    };

    omesaasProduct.prototype.isCurrentOptionBuy = function (item) {
        
        
        
        
        
        return item.available ? true : false;
    };

    omesaasProduct.prototype.optionIndexKey = function (index) {
        return { title: `option${index + 1}_title`, value: `option${index + 1}_value_title`, id: `option${index + 1}_value` };
    };
    
    omesaasProduct.prototype.getColorValue = function (name) {
        if (window.themeConfig && window.themeConfig.global.product_sku_style && window.themeConfig.global.product_sku_style == "color") {
            if (window._sku_color_ && window._sku_color_[name]) {
                return window._sku_color_[name];
            }
        }
        return name;
    };

    
    omesaasProduct.prototype.getOptional = function (sku) {
        for (let i = 0; i < sku.length; i++) {
            const element = sku[i];
            if (this.isCurrentOptionBuy(element)) {
                return element;
            }
        }
        return false;
    };

    
    omesaasProduct.prototype.setAllSkuOption = function () {
        const checkedSkuInfo = this.checkedSKu();

        let product_sku_options = themeConfig.global.product_sku_options || [];
        product_sku_options = product_sku_options.map((item) => item.toLowerCase());

        this.variant = this.variant.map((item, index) => {
            const hasColorCard = ["option1_title", "option2_title", "option3_title"].some((title) =>
                product_sku_options.includes(item[title].toLowerCase())
            );
            
            if (hasColorCard) {
                item["colorCard"] = true;
            }
            const values = ["option1_value_title", "option2_value_title", "option3_value_title"].map((value) => item[value]);
            item["colorValue"] = this.getColorValue(values[0]);

            item["name"] = values.filter((value) => value).join("/");

            
            if (storeConfig.checked_first_sku != 2 && index === 0 && item.available) {
                item["checked"] = true;
                this.setSelectedVal(item);
                this.setPriceVal(item);
            }

            
            if (checkedSkuInfo && checkedSkuInfo.sku_code === item.sku_code) {
                item["checked"] = true;
                this.setSelectedVal(item);
                this.setPriceVal(item);
            }

            return item;
        });
        
        
        if(this.product.inventory_tracking != 0 && [1,3].includes(this.product.inventory_policy) && storeConfig.sold_out_style == 2) {
            this.variant = this.variant.filter((item) => item.available != 0);
        }

        this.render();
    };

    omesaasProduct.prototype.setSkuOption = function () {
        if (this.productOptionType === "all") {
            this.setAllSkuOption();
            return;
        }
        let filterSKu = JSON.parse(JSON.stringify(this.variant));
        let options = [...this.product.options];
        let product_sku_options = [];
        let currentSkuItem = null;
        if (themeConfig.global.product_sku_options) {
            product_sku_options = themeConfig.global.product_sku_options.map(function (item) {
                return item.toLowerCase();
            });
        }
        let isSetOptionImg = false;
        this.attrOption.map((attr, i) => {
            attr.optionsValue = options[i].values.map((k) => k.option_value);
            const { title, value, id } = this.optionIndexKey(i);
            filterSKu.forEach((item) => {
                if (!attr.name) {
                    attr.name = item[title];
                    if (
                        product_sku_options &&
                        product_sku_options.indexOf(attr.name.toLowerCase()) > -1 &&
                        (!isSetOptionImg || themeConfig.global.product_sku_style === "color")
                    ) {
                        attr.isImg = true;
                        isSetOptionImg = true;
                    }
                }

                const currentIndex = attr.value.findIndex((val) => val.name === item[value]);
                if (currentIndex > -1) {
                    attr.value[currentIndex].quantity += item.inventory_quantity;
                    if (!attr.value[currentIndex].available && item.available) {
                        attr.value[currentIndex].available = item.available;
                    }
                } else {
                    var currentMultiple = this.multiple.find((el) => el.id === item.id);

                    attr.value.push({
                        name: item[value],
                        colorValue: this.getColorValue(item[value]),
                        value: item[id],
                        id: item.id,
                        available: item.available,
                        price: item.price,
                        formatPrice: formatMoney(item.price, oemcart_currency),
                        deleteItem: item.deleteItem || false,
                        image: item.image || "",
                        sku_code: item.sku_code,
                        sku: item.sku,
                        sku_value: item.sku_value,
                        
                        add_quantity: currentMultiple ? currentMultiple.add_quantity : 0,
                        option1_value: item.option1_value,
                        option2_value: item.option2_value,
                        option3_value: item.option3_value,
                        quantity: item.inventory_quantity
                    });
                    attr.deleteSelect = "";
                }
            });
            
            if (attr.selected_value) {
                const currentOption = attr.value.filter((el) => el.value === attr.selected_value);
                
                if (!currentOption.length) {
                    const option = this.getOptional(filterSKu);
                    attr.selected_value = option[id];
                    attr.selected_value_label = option[value];
                }

                filterSKu = filterSKu.filter((el) => el[id] === attr.selected_value);
                
                if (!filterSKu.length) {
                    attr.selected_value = "";
                    attr.selected_value_label = "";
                    this.setSelectedVal(false);
                    currentSkuItem = { available: 1 };
                }

                
                if (i === this.attrOption.length - 1 && filterSKu.length == 1 && attr.selected_value) {
                    this.setSelectedVal(filterSKu[0]);
                    this.setPriceVal(filterSKu[0]);
                    currentSkuItem = filterSKu[0];
                }
            } else {
                currentSkuItem = this.variant[0];
                this.setPriceVal(this.variant[0]);
                const newParams = Object.assign({}, this.params);
                newParams["image"] = this.product.image;
                newParams["sku_code"] = ""; 
                moi.onEvent("productOptionChange", newParams);
            }

            
            if (storeConfig.combination == 1) {
                if (attr.value.length != attr.optionsValue.length) {
                    attr.optionsValue.forEach((item, index) => {
                        let hasItem = attr.value.filter((i) => i.name == item);
                        if (hasItem.length === 0) {
                            let hasThisSuk = this.product.variants.filter((imageItem) => imageItem[value] == item);
                            attr.value.push({
                                name: item,
                                colorValue: item,
                                deleteItem: true,
                                available: 0,
                                value: hasThisSuk.length ? hasThisSuk[0][id] : new Date().getTime(),
                                image: hasThisSuk.length ? hasThisSuk[0].image : { src: "" }
                            });
                        }
                    });
                    
                    attr.value = attr.value.sort((a, b) => {
                        return attr.optionsValue.indexOf(a.name) - attr.optionsValue.indexOf(b.name);
                    });
                }
            }
           
            
            if(this.product.inventory_tracking != 0 && [1,3].includes(this.product.inventory_policy) && storeConfig.sold_out_style == 2) {
                attr.value = attr.value.filter(item => item.available !== 0 || item.deleteItem);
            }
            
            return attr;
        });
        
        
        if(this.product.inventory_tracking != 0 && [1,3].includes(this.product.inventory_policy) && storeConfig.sold_out_style == 2) {
            this.attrOption.forEach((item) => {
                if(item.value.length == 0) {
                    this.skuNode.find(`div[data-sku-name="${item.name}"]`).hide();
                }else {
                    this.skuNode.find(`div[data-sku-name="${item.name}"]`).show();
                }
            })
        }
       
       
        this.render(currentSkuItem);
        
    };

    
    omesaasProduct.prototype.setPriceVal = function (currentSku) {
        
        let product_price_display = window.themeConfig.global.product_price_display || 0;
        let price = 0;
        let comparePrice = 0;

        if (this.renderOption) {
            if (storeConfig.checked_first_sku == 2 && this.renderFirst) {
                if (product_price_display == 0) {
                    price = currentSku.price;
                    comparePrice = currentSku.compare_at_price;
                } else if (product_price_display == 1) {
                    price = this.product.variant_price_min;
                    comparePrice = this.product.variant_compare_at_price_min;
                } else if (product_price_display == 2) {
                    price = this.product.variant_price_max;
                    comparePrice = this.product.variant_compare_at_price_max;
                } else {
                    price = this.product.variant_price_min;
                    comparePrice = this.product.variant_price_max;
                }
                if (product_price_display == 3) {
                    let text =
                        price < comparePrice
                            ? `${formatMoney(price, oemcart_currency)} - ${formatMoney(comparePrice, oemcart_currency)}`
                            : `${formatMoney(price, oemcart_currency)}`;
                    this.numberNode.html(text);
                } else {
                    this.numberNode.html(formatMoney(price, oemcart_currency));
                }
            } else {
                price = currentSku.price;
                comparePrice = currentSku.compare_at_price;
                this.numberNode.html(formatMoney(price, oemcart_currency));
            }

            this.skuValueNode.html(currentSku.sku);

            if (parseFloat(comparePrice) > parseFloat(price)) {
                if (storeConfig.checked_first_sku == 2 && this.renderFirst) {
                    if (product_price_display == 3) {
                        this.marketNode.html("");
                    } else {
                        this.marketNode.html(formatMoney(comparePrice, oemcart_currency));
                    }
                } else {
                    this.marketNode.html(formatMoney(comparePrice, oemcart_currency));
                }

                if (window.themeConfig.global.product_discount_label_style_switch) {
                    let disPrice = 0;
                    let disComparePrice = 0;
                    if (storeConfig.checked_first_sku == 2 && this.renderFirst && product_price_display == 3) {
                        disPrice = this.product.variant_price_min;
                        disComparePrice = this.product.variant_compare_at_price_min;
                    } else {
                        disPrice = price;
                        disComparePrice = comparePrice;
                    }

                    if (disComparePrice == 0) {
                        this.marketNode.html("");
                        this.discountNode.hide();
                        return;
                    }

                    
                    if (window.themeConfig.global.product_discount_label_style == 2) {
                        this.discountNode.html(
                            lang.general.save + " " + Math.floor((1 - parseFloat(disPrice) / parseFloat(disComparePrice)) * 100) + "%"
                        );
                    } else {
                        this.discountNode.html(
                            lang.general.save + " " + formatMoney((parseFloat(disComparePrice) - parseFloat(disPrice)).toFixed(2), oemcart_currency)
                        );
                    }

                    this.discountNode.show();
                }
            } else {
                this.marketNode.html("");
                this.discountNode.hide();
            }
        }
    };

    
    omesaasProduct.prototype.setSelectedVal = function (currentSku) {
        const product = this.product;
        const params = this.params;
        if (!currentSku) {
            this.params = {
                src: product.src,
                productTitle: product.title,
                product_id: product.id,
                sku_value: "",
                quantity: params.quantity || 1
            };
        } else {
            this.params = Object.assign(params, currentSku);
            // 处理如果只是修改购买数量添加标识
            const updateKeys = Object.keys(currentSku);
            if(updateKeys.length === 1 && updateKeys[0] === 'quantity'){
                this.params['changeType'] = 'quantity';
            }
   
         
            if (this.optionLength && this.params.sku) {
                let skuName = [];
                for (let i = 0; i < this.optionLength; i++) {
                    const title = this.params[`option${i + 1}_title`];
                    const value = this.params[`option${i + 1}_value_title`];
                    skuName.push(`${title}:${value}`);
                }
                this.params["sku_value"]  = skuName.join("<br/>");
            }
        }

        
        if (location.pathname.indexOf("/products") !== -1 && this.params.sku_code && this.isMainProduct && !this.renderFirst) {
            history.replaceState(null, null, moi.setUrlParams(location.href, { variant_sku_code: this.params.sku_code }));
        }

        
        if (this.isMainProduct) {
            $(".mo-editor-reset")
                .find("img")
                .each(function (index, element) {
                    $(this).attr("referrer", "no-referrer");
                });
            moi.setPageStorage("mian_product_params", this.params);
            
            if (this.product.status === 0 && moi.getUrlParam("preview")) {
                moi.addEvent("payVerified", function (event) {
                    event.stopPropagation();
                    event.params["code"] = 400;
                    moi.alertInfo({ content: "当前为预览链接不可操作" });
                });
            }
        }
        moi.onEvent("productOptionChange", this.params);
        
        moi.setPageStorage("product_params" + this.block_id, this.params);
        this.changeOption && this.changeOption.call(this, this.params);
    };

    omesaasProduct.prototype.optionCompare = function (html, currentSkuItem) {
        const skuNode = $(`<div>${html}</div>`);
        if (this.oldAttrOption.length) {
            this.attrOption.forEach((item, index) => {
                if (item.selected_value !== this.oldAttrOption[index].selected_value) {
                    const valIndex = item.value.findIndex((val) => val.value === item.selected_value);
                    if (valIndex > -1) {
                        const currentNode = this.skuNode.find(".moi-product-sku-value").eq(index).find(".product-sku-values-item").eq(valIndex);
                        const labelNode = this.skuNode.find(".moi-product-sku-label").eq(index);
                        currentNode.addClass("product-sku-values-item-active").siblings().removeClass("product-sku-values-item-active");
                        labelNode.html(skuNode.find(".moi-product-sku-label").eq(index).html());
                    }
                    
                    if (item.selected_value == "") {
                        this.skuNode
                            .find(".moi-product-sku-value")
                            .eq(index)
                            .find(".product-sku-values-item")
                            .removeClass("product-sku-values-item-active");
                    }
                }

                var availabIsEqual =
                    item.value.map((el) => el.available).toString() != this.oldAttrOption[index].value.map((el) => el.available).toString();
                var itemIsEqual = item.value.map((el) => el.value).toString() !== this.oldAttrOption[index].value.map((el) => el.value).toString();
                
                if (itemIsEqual || availabIsEqual) {
                    this.skuNode.find(".moi-product-sku-value").eq(index).html(skuNode.find(".moi-product-sku-value").eq(index).html());
                } else {
                    if (this.isMultiple() && this.optionLength - 1 === index) {
                        this.skuNode.find(".moi-product-sku-value").eq(index).html(skuNode.find(".moi-product-sku-value").eq(index).html());
                    }
                }
            });
        } else {
            this.skuNode.html(html);
            this.event();
        }

        if (currentSkuItem) {
            let can_buy = true;
            let showBtnType = "stockout";

            this.skuNode.find(".product-sku-values-item-disable").each((elemIndex, elem) => {
                if (!can_buy) return;
                if ($(elem).hasClass("product-sku-values-item-active")) {
                    if ($(elem).attr("is_deleteProduct") == "true") {
                        showBtnType = "delete";
                    } else {
                        showBtnType = "stockout";
                    }
                    can_buy = false;
                }
            });
            if (!can_buy) {
                this.setButtonGroup(currentSkuItem, showBtnType);
            } else {
                this.setButtonGroup(currentSkuItem, null);
            }
        }

        this.oldAttrOption = JSON.parse(JSON.stringify(this.attrOption));
    };

    
    omesaasProduct.prototype.setMultipleOption = function (currentSkuItem) {
        let length = this.attrOption.length;
        if (length <= 2 && length !=0 && this.isMultiple()) {
            this.attrOption[length - 1]["type"] = "multiple";
        }
    };

    
    omesaasProduct.prototype.pushMultiple = function (item) {
        const index = this.multiple.findIndex((el) => el.id === item.id);
        if (index === -1) {
            this.multiple.push(item);
        } else {
            this.multiple[index].add_quantity = item.add_quantity;
        }
    };

    
    omesaasProduct.prototype.resetMultiple = function (value) {
        this.multiple.forEach((item) => {
            if (item.option1_value === value || !value) {
                item.add_quantity = 0;
            }
        });
    };

    omesaasProduct.prototype.updateMultipleAngle = function () {
        if (this.attrOption.length >= 2) {
            let angle = {};
            this.multiple.forEach((item) => {
                angle[item.option1_value] = item.add_quantity + (angle[item.option1_value] || 0);
            });
            Object.keys(angle).forEach((key) => {
                var angleNode = $(".multiple-angle[data-id=" + key + "]");
                if (!angle[key]) {
                    angleNode.hide();
                } else {
                    $(".multiple-angle[data-id=" + key + "]")
                        .text("x" + angle[key])
                        .show();
                }
            });
        }
    };

    
    omesaasProduct.prototype.multipleTotalPrice = function () {
        var multiple = this.multiple;
        var multipleTotalNode = $(".multiple-total");
        var variant = multipleTotalNode.find(".variant");
        var item = multipleTotalNode.find(".item");
        var multipleTotal = multipleTotalNode.find(".multiple-total-value");
        variant.text(multiple.filter((item) => item.add_quantity).length);
        item.text(multiple.map((item) => item.add_quantity).reduce((a, b) => parseFloat(a) + parseFloat(b), 0));
        var price = multiple
            .filter((item) => item.add_quantity)
            .map((item) => parseFloat(item.price).times(item.add_quantity))
            .reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
        multipleTotal.text(formatMoney(price, oemcart_currency));
        this.updateMultipleAngle();
    };

    
    omesaasProduct.prototype.render = function (currentSkuItem) {
        if (this.renderOption) {
            this.setMultipleOption();
            const self = this;
            let unlimited = false;
            if(!this.product.inventory_tracking || (this.product.inventory_tracking && this.product.inventory_policy == 2)){
                unlimited = true
            }
            engine
                .parseAndRender(this.skuTemplate, {
                    inventory_tracking: this.product.inventory_tracking,
                    skus: this.attrOption,
                    variant: this.variant,
                    unlimited:unlimited,
                    lang: lang,
                    checkedFirstSku: storeConfig.checked_first_sku,
                    productSkuStyle: themeConfig.global.product_sku_style || "image_text",
                    productSkuSize: "sku-image-item-" + themeConfig.global.product_sku_size || "mall"
                })
                .then(function (liquidHtml) {
                    self.optionCompare(liquidHtml, currentSkuItem);
                    if (self.productOptionType === "all") {
                        let skuBg = moi.hexToRgba(themeConfig.global.main_button_bg, 0.06);
                        let skuBorder = moi.hexToRgba(themeConfig.global.main_button_bg, 0.4);
                        self.skuNode[0].style.setProperty("--sku-bg", skuBg);
                        self.skuNode[0].style.setProperty("--sku-border", skuBorder);
                    }
                    if (self.isMultiple()) {
                        self.multipleTotalPrice();
                    }
                    
                });
        }
        if (!this.product.available) {
            this.setSelectedVal({ quantity: this.params.quantity });
            this.discountNode.hide();
        }
    };

    
    omesaasProduct.prototype.verifyOption = function (type) {
        if(this.isMainProduct){
            if (moi.isEvent("cancelAddCart") && type === 'cart'){
                   moi.onEvent("cancelAddCart")
       
                   return false
       
               }
               if (moi.isEvent("cancelBuynow") && type === 'buy'){
                   moi.onEvent("cancelBuynow")
       
                   return false
       
               }
           }
      

        
        if (this.product.available === 0) {
            moi.alertInfo({ content: lang.checkout.quantity_empty });
            return false;
        }

        
        if (this.product.status === 0 && moi.getUrlParam("preview")) {
            moi.alertInfo({ content: "当前为预览链接不可操作" });
            return false;
        }

        if (type === "cart" && !this.cartShake) {
            return false;
        }

        if (type === "buy" && !this.buyShake) {
            return false;
        }

        if (this.productOptionType !== "all" ) {
            for (let i = 0; i < this.attrOption.length; i++) {
                if (!this.attrOption[i].selected_value && this.attrOption[i].type != "multiple" ) {
                    $("html, body").animate({ scrollTop: this.skuNode.find(".product-sku-name").eq(i).offset().top - 200 });
                    moi.tooltip({
                        placement: "right",
                        el: this.skuNode.find(".product-sku-name").eq(i),
                        content: lang.product.please_select_sku.replace("{sku}", this.product.options[i].name)
                    });
                    return false;
                }
            }
        }
    
        
        if (this.isMultiple() && !this.multiple.filter((item) => item.add_quantity).length ) {
            moi.alertInfo({ content: lang.checkout.quantity_empty });
            return;
        }

        if (this.productOptionType === "all" && !this.params.sku_value && this.optionLength) {
            $("html, body").animate({ scrollTop: this.skuNode.find(".sku_option-template_all").eq(0).offset().top - 200 });
            moi.alertInfo({ content: lang.product.please_select_sku.replace("{sku}", this.product.options[0].name) });
            return;
        }
      
       

        return true;
    };

    
    omesaasProduct.prototype.getEcData = function () {
        const self = this;
        return {
            ec_data_id: self.product.id,
            ec_data_from: self.data_from,
            ec_data_name: encodeURIComponent(self.product.title),
            ec_data_price: self.params.price,
            ec_data_discount_price: self.params.price,
            ec_data_spu: self.product.spu,
            ec_data_image: self.product.src,
            ec_data_category: self.product.product_type,
            ec_data_uniq_id: self.product.id,
            ec_data_sku: self.params.sku,
            ec_data_sku_code: self.params.sku_code,
            ec_data_quantity: self.params.quantity,
            ec_data_sku_name: self.params.sku_value || "",
            ec_currency_code: self.ec_currency_code,
            ec_data_action_type: ""
        };
    };

    omesaasProduct.prototype.share = function (platform) {
        const self = this;
        const ec_data = {
            ec_data_id: self.product.id,
            ec_data_from: self.data_from,
            ec_data_name: encodeURIComponent(self.product.title),
            ec_data_price: self.product.variant.price,
            ec_data_discount_price: self.product.variant.price,
            ec_data_spu: self.product.spu,
            ec_data_image: self.product.src,
            ec_data_category: self.product.product_type,
            ec_data_uniq_id: self.product.id,
            ec_data_sku: self.product.variant.sku,
            ec_data_sku_code: self.product.variant.sku_code,
            ec_data_quantity: 1,
            ec_data_sku_name: self.product.variant.sku_value,
            ec_currency_code: self.ec_currency_code,
            ec_data_action_type: ""
        };
        ec_data.ec_data_action_type = "share_product";
        callback_share_product(ec_data, platform);
    };

    
    omesaasProduct.prototype.callbackAddToCart = function () {
        const self = this;
        const ec_data = self.getEcData();
        ec_data.ec_data_action_type = "add_to_cart";
        callback_add_to_cart(ec_data);
    };

    
    omesaasProduct.prototype.getCustomAttr = function (attr) {
        return attr
            .filter((el) => el.params)
            .map((el) => {
                let params = el.params;
                let value = "";
                if (["checkbox", "image_group", "block_text", "image"].includes(el.type)) {
                    value = params.map((param) => {
                        const current = el.rule.selected.find((select) => select.name == param.value);
                        return {
                            value: current.name,
                            price: current.price || 0,
                            urls: param.url || current.other || ""
                        };
                    });
                } else {
                    value = params.value;
                }

                return {
                    type: el.type,
                    value: value,
                    name: el.title,
                    price: el.price,
                    urls: el.type === "file" ? params.url : ""
                };
            });
    };

    omesaasProduct.prototype.callbackMultipleAddToCart = function () {
        const self = this;

        this.multiple.forEach((item) => {
            const ec_data = {
                ec_data_id: this.product.id,
                ec_data_from: this.data_from,
                ec_data_name: encodeURIComponent(this.product.title),
                ec_data_price: item.price,
                ec_data_discount_price: item.price,
                ec_data_spu: this.product.spu,
                ec_data_image: this.product.src,
                ec_data_category: this.product.product_type,
                ec_data_uniq_id: this.product.id,
                ec_data_sku: item.sku,
                ec_data_sku_code: item.sku_code,
                ec_data_quantity: item.add_quantity,
                ec_data_sku_name: item.sku_value || "",
                ec_currency_code: this.ec_currency_code,
                ec_data_action_type: "add_to_cart"
            };
            callback_add_to_cart(ec_data);
        });
    };
    omesaasProduct.prototype.multipleAddCart = function (complete, success) {
        const self = this;
        self.cartShake = false;
        var addMultiple = this.multiple.filter((item) => item.add_quantity);
        var params = addMultiple.map((item) => {
            return {
                product_id: this.product.id,
                sku_code: item.sku_code,
                quantity: item.add_quantity,
                data_from: self.data_from,
                property: []
            };
        });
        moi.ajax({
            url: "/cart/batched",
            type: "post",
            data: JSON.stringify(params),
            complete() {
                self.cartShake = true;
            },
            success: function (data) {
                complete && complete.call(this);
                if (!data.code) {
                    moi.onEvent("cartChange", data.data);
                    moi.changeCartNumber(data.data.item_count);
                    miniCart();
                    if (window.callback_add_to_cart) {
                        self.callbackMultipleAddToCart();
                    }
                    self.setSelectedVal({ subtotalPrice: data.data.items_subtotal_price });
                }
                success && success.call(self, data);
            }
        });
    };
    
    omesaasProduct.prototype.addCart = function (complete, success, isMiniCart = true) {
        const self = this;
        if (this.isMultiple()) {
            this.multipleAddCart(complete, success);
            return;
        }
        self.cartShake = false;
        let ret = moi.onEvent("payVerified", { property: [], custom_attr: [], product: this.params, code: 200 });
        if (ret.params.code === 200) {
            self.params["property"] = ret.params.property;

            moi.ajax({
                url: "/cart/add",
                type: "post",
                data: JSON.stringify({
                    
                    
                    product_id: this.product.id,
                    sku_code: this.params.sku_code,
                    quantity: this.params.quantity,
                    data_from: self.data_from,
                    property: ret.params.property
                }),
                complete() {
                    self.cartShake = true;
                },
                success: function (data) {
                    complete && complete.call(this);
                    
                    if (ret.params.original && data.data) {
                       self.params["custom_attr"] = data.data.items[data.data.items.length - 1].property.filter(el=>el.type !== "app_minmaxoffer");
                    }

                    if (!data.code) {
                        moi.onEvent("cartChange", data.data);
                        self.product["cart"] = data.data;
                        moi.onEvent("addToCart", self.product);
                        if (window.callback_add_to_cart) {
                            self.callbackAddToCart();
                        }
                        moi.changeCartNumber(data.data.item_count);
                        isMiniCart && miniCart();
                        self.setSelectedVal({ subtotalPrice: data.data.items_subtotal_price });
                    }
                    success && success.call(self, data);
                }
            });
        } else {
            self.cartShake = true;
            complete && complete.call(this);
        }
    };

    omesaasProduct.prototype.multipleBuynow = function (complete, success,isDefault) {
        const self = this;
        self.cartShake = false;
        var addMultiple = this.multiple.filter((item) => item.add_quantity);
        var params = addMultiple.map((item) => {
            return {
                product_id: this.product.id,
                sku_code: item.sku_code,
                quantity: item.add_quantity,
                data_from: self.data_from,
                property: []
            };
        });
        moi.ajax({
            url: "/cart/batchbuynow",
            type: "post",
            data: JSON.stringify({ data: params }),
            complete() {
                self.cartShake = true;
            },
            success: function (ret) {
                complete && complete.call(this);
                if (ret.data && ret.data.code == -1000) {
                    alert(ret.data.msg);
                    return;
                }
                if (!ret.code) {
                    if (window.callback_add_to_cart) {
                        self.callbackMultipleAddToCart();
                    }
                    if (ret.data.checkout_url && moi && isDefault) {
                        ret.data.checkout_url = moi.setUrlParams(ret.data.checkout_url, { _ref: location.href });
                    }
                }
                success && success.call(self, ret);
            }
        });
    };

    omesaasProduct.prototype.buynow = function (complete, success,isDefault = true) {
        const self = this;
        if (this.isMultiple()) {
            this.multipleBuynow(complete, success,isDefault);
            return;
        }
        self.buyShake = false;
        let ret = moi.onEvent("payVerified", { property: [], product: this.params, code: 200 });
        if (ret.params.code === 200) {
            self.params["property"] = ret.params.property;
            moi.ajax({
                url: "/cart/buynow",
                type: "post",
                data: JSON.stringify({
                    product_id: this.product.id,
                    sku_code: this.params.sku_code,
                    quantity: this.params.quantity,
                    data_from: self.data_from,
                    property: ret.params.property
                }),
                complete() {
                    self.buyShake = true;
                },
                success: function (ret) {
                    complete && complete.call(this);

                    if (ret.data && ret.data.code == -1000) {
                        alert(ret.data.msg);
                        return;
                    }
                    if (!ret.code) {
                        moi.onEvent("buynow", self.product);

                        if (!ret.code && window.callback_add_to_cart) {
                            self.callbackAddToCart();
                        }
                        if (ret.data.checkout_url && moi && isDefault) {
                            ret.data.checkout_url = moi.setUrlParams(ret.data.checkout_url, { _ref: location.href });
                        }
                    }
                    success && success.call(self, ret);
                }
            });
        } else {
            self.buyShake = true;
            complete && complete.call(this);
        }
    };

    
    omesaasProduct.prototype.cartLayer = function () {
        
        if (storeConfig.purchase_style == 2) {
            moi.alertInfo({ content: lang.product.add_cart_succeed, placement: "top", type: "success" });
            return;
        }
        if (storeConfig.purchase_style == 3) {
            showMiniCart();
            return;
        }

        if (storeConfig.purchase_style == 4) {
            location.href = "/cart";
            return;
        }

        if (this.isMultiple()) {
            showMiniCart();
            return;
        }

        const option = JSON.parse(JSON.stringify(this.params));
        let isProperty = false; 
        if (option.property && option.property.length) {
            isProperty = option.property.some((el) => typeof el.params !== "string");
        }
        const subtotalPrice = formatMoney(parseFloat(option.subtotalPrice || 0), oemcart_currency);
        const popupLayer = moi.popup();
        var html = $("#id-popup-addPurchase-success").length?$("#id-popup-addPurchase-success").html():$("#omesaas-popup-addPurchase-success").html();
        engine
            .parseAndRender(html, {
                option: option,
                subtotalPrice: subtotalPrice,
                isProperty: isProperty,
                storeConfig: storeConfig,
                lang: window.lang
            })
            .then(function (html) {
                popupLayer.addContent(html);
                const temp = popupLayer.temp;
                
                const submitNodes = temp.find(".cart-buyNow");

                submitNodes.on("click", function () {
                    temp.find(".cart_form").submit();
                    popupLayer.close();
                });
            });
    };

    





    omesaasProduct.prototype.renderProductImgList = function (params = {}) {
        let config = {
            isUpdate: false,
            parentsClass: ".collection_item",
            defaultImgClass: ".default_img",
            ...params
        };

        function renderImgList() {
            $(".block_product_img_list.noRender").each((index, elem) => {
                let width = $(elem).width() - $(elem).width() * 0.26;
                let renderMaxLength = Math.floor(width / 28);
    
                let listDom = $(elem).find(".img_list .img_list_item");
                let listDomLen = listDom.length > renderMaxLength ? "+" + (listDom.length - renderMaxLength) : "";
                $(elem).find(".img_list .morNumber").text(listDomLen);
                listDom.each((itemIndex, listItem) => {
                    if (itemIndex >= renderMaxLength) {
                        $(listItem).remove();
                    }
                });
                $(elem).removeClass("noRender");
                listDom.on("mouseenter", function () {
                    let src = $(this).find("img").attr("src").split("?")[0];
                    var defaultImgNode = config.isUpdate
                        ? $(this).parents(config.parentsClass).find(config.defaultImgClass)
                        : $(this).parent().parent().parent().find(".default_img");
                    defaultImgNode.attr("data-src", src);
                    window.lazyLoadImage(defaultImgNode);
                    $(this).addClass("active").siblings().removeClass("active");
                });
            });
        }
        renderImgList()
        moi.addEvent("updateBlock",function(e){
            renderImgList()
        })
    };

    omesaasProduct.prototype.wishlistParams = function (value, hit_type_category) {
        var ec_data = this.getEcData();
        ec_data.ec_data_action_type = "view_content";
        ec_data.ec_data_from = "wishlist";
        function getMetaContent(metaName) {
            const metas = document.getElementsByTagName("meta");
            for (let i = 0; i < metas.length; i++) {
                if (metas[i].getAttribute("name") === metaName) {
                    return metas[i].getAttribute("content");
                }
            }
            return "";
        }
        const collectParams = {
            hit_type_category: hit_type_category,
            hit_type_name: "wish_product",
            hit_type_lable: "product",
            ec_data: ec_data,
            hit_type: "event",
            hit_type_value: value,
            pv_id: window.oemcart_pv_id || "",
            store_id: window.oemcart_store_id || "",
            document_location_url: encodeURIComponent(window.location.href),
            document_location_title: document.title,
            meta_keywords: getMetaContent("keywords"),
            prev_url: document.referrer,
            vid: window.oemcart_global_unique_id || "",
            rnd: Math.random()
        };
        return collectParams;
    };

    
    omesaasProduct.prototype.wishlistEvent = function () {
        var wishlistNode = $(this.wishlist);
        var that = this;

        if (that.wishlistShake) {
            this.wishlistShake = false;
            wishlistNode.click(function () {
                $(this).find(".wishlist-animated").addClass("animated tada");
                setTimeout(() => {
                    $(this).find(".wishlist-animated").removeClass("animated tada");
                }, 700);
                
                if (!oemcart_user_id) {
                    location.href = "/account/login?checkout_url=" + encodeURIComponent(location.href);
                    return;
                }
                if (that.product.in_wishlist == 1) {
                    that.product.in_wishlist = 0;
                    wishlistNode.removeClass("product-wishlist-active");
                    moi.ajax({
                        url: "/wishlist",
                        type: "DELETE",
                        data: JSON.stringify({
                            product_id: that.product.id,
                            event: that.wishlistParams(0, "remove_from_wishlist")
                        }),
                        complete() {
                            that.wishlistShake = true;
                        },
                        success: function (ret) {
                            if (!ret.code) {
                                moi.alertInfo({ content: lang.product.remove_from_wishlist, type: "success", placement: "top" });
                            } else {
                                moi.alert({ title: ret.msg });
                            }
                        }
                    });
                } else {
                    that.product.in_wishlist = 1;
                    wishlistNode.addClass("product-wishlist-active ");
                    moi.ajax({
                        url: "/wishlist",
                        type: "POST",
                        data: JSON.stringify({
                            product_id: that.product.id,
                            event: that.wishlistParams(1, "add_to_wishlist")
                        }),
                        complete() {
                            that.wishlistShake = true;
                        },
                        success: function (ret) {
                            if (!ret.code) {
                                moi.alertInfo({ content: lang.product.add_to_wishlist, type: "success", placement: "top" });
                                callback_add_to_wishlist && callback_add_to_wishlist(that.getEcData());
                            } else {
                                moi.alert({ title: ret.msg });
                            }
                        }
                    });
                    
                }
            });
        }
    };

    window.omesaasProduct = omesaasProduct;
    window.shopProduct = omesaasProduct;

    function handleBuyNow(event) {
        console.warn('handleBuyNow',event);
        var eventData = event.data.data;
        moi.ecBuyNow(eventData,true,event)
    }
 
    function handleIframeResize(event) {
      console.warn('handleIframeResize',event);
      const iframe = document.getElementById('ec-payment-div-'+window['ec_action_from']);
      if (event.data.data.fullscreen) {
        if(window['ec_action_from'] === "product_detail"){
         $(".product-right").css("z-index", "999999999");
        }
        iframe.style.width = '100vw';
        iframe.style.height = '100vh';
        iframe.style.position = 'fixed';
        iframe.style.top = '0';
        iframe.style.zIndex = '1000';
        iframe.style.left = '0';
        iframe.style.marginTop = '0';
      } else {
        if(window['ec_action_from'] === "product_detail"){
            $(".product-right").css("z-index", "1");
        }
        iframe.style.position = 'relative';
        iframe.style.width = '100%';
        iframe.style.height = '80px';
        iframe.style.marginTop = '10px';
      }
    }
    
    function handleRequest(event) {
      handleIframeResize({data:{data:{fullscreen:false}}})

      const retData = event.data;
        createAjaxLoading()

      fetch(retData.data.url, {
        method: 'POST',
         headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ...retData.data.data,
          capture_url:retData.data.capture_url
        })
      }).then(function (res) {
            removeAjaxLoading()
        return res.json();
      }).then(function (ret) {
        if (ret.code == 0) {
          location.href = ret.data.redirect_url;
        }else {
          moi.alertInfo({ content: ret.data.msg });
          return false;
        }
      });
    }

    
    window.addEventListener('message', function (e) {
      try {
        const message = typeof e.data === 'string' ? JSON.parse(e.data) : e.data;

        if (!message.type) {
          return;
        }

        switch (message.type) {
          case 'shop_buynow':
            handleBuyNow(e);
            break;
          case 'shop_iframeResize':
            handleIframeResize(e);
            break;
          case 'shop_ecData':
            handleRequest(e);
            break;
          default:
            
        }
      } catch (error) {
        
      }
    });
})();
